package com.neusoft.hifly.attachment.file.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.neusoft.hifly.attachment.file.dao.IFileDownDao;
import com.neusoft.hifly.attachment.file.entity.FileDownObj;
import com.neusoft.hifly.attachment.file.service.IFileDownService;
import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.commons.lang.StringConstants;
import com.neusoft.hifly.core.basic.service.impl.CTSaaSBaseServiceImpl;
import com.neusoft.hifly.dynamicds.multi.annotation.MultiDynamicRoutingDataSource;

/**
 * Title: 附件服务
 * <p>
 * Description: 附件_附件下载记录表 Service
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service
@MultiDynamicRoutingDataSource
public class FileDownServiceImpl extends CTSaaSBaseServiceImpl implements IFileDownService {
	@Autowired(required = false)
	private IFileDownDao fileDownDao;

	/**
	 * 保存对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param obj
	 *            对象
	 * @throws SystemErrorException
	 *             自定义异常
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void saveOrUpdate(final String organCode, final long organLogicId, final FileDownObj obj)
			throws SystemErrorException {
		if (StringUtils.isEmpty(organCode) || obj == null) {
			return;
		}

		final FileDownObj oldObj = fileDownDao.getById(organCode, obj.getId());

		obj.setOrganLogicId(organLogicId);

		// 有ID的话要判断是否保存还是更新
		if (oldObj == null) {
			// 保存

			obj.setDownloadTime(LocalDateTime.now());

			this.setForm(obj, obj);

			fileDownDao.insert(obj);

		} else {
			// 更新

			this.setForm(obj, oldObj);
			oldObj.setDownloadTime(LocalDateTime.now());
			fileDownDao.updateById(oldObj);

		}
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param id
	 *            对象ID
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteById(final String organCode, final int id) {
		if (StringUtils.isEmpty(organCode)) {
			return;
		}

		fileDownDao.deleteById(organCode, id);
	}

	/**
	 * 批量删除对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param ids
	 *            对象ID，多id使用英文逗号分隔
	 */
	@Override
	public void deleteByBatch(final String organCode, final String ids) {
		if (StringUtils.isEmpty(organCode) || StringUtils.isEmpty(ids)) {
			return;
		}
		final String[] idArr = ids.split(StringConstants.STRING_SPLIT_FLAG_3);
		if (idArr == null) {
			return;
		}
		for (final String id : idArr) {
			if (StringUtils.isEmpty(id) || !StringUtils.isNumeric(id)) {
				continue;
			}
			this.deleteById(organCode, Integer.parseInt(id));
		}
	}

	/**
	 * 根据id查询对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param id
	 *            对象ID
	 * @return 对象
	 */
	@Override
	public FileDownObj getById(final String organCode, final int id) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return fileDownDao.getById(organCode, id);
	}

	/**
	 * 查询所有对象
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @return 对象集合
	 */
	@Override
	public List<FileDownObj> findAll(final String organCode, final long organLogicId) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		return fileDownDao.findAll(organCode, organLogicId);
	}

	/**
	 * 根据条件查询
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 集合
	 */
	@Override
	public List<FileDownObj> search(final String organCode, final long organLogicId, Map<String, Object> property) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		if (property == null) {
			property = new HashMap<String, Object>(1);
			property.put("organLogicId", organLogicId);
		}
		final QueryWrapper<FileDownObj> queryWrapper = new QueryWrapper<FileDownObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "DOWNLOAD_TIME" });
		return fileDownDao.selectList(queryWrapper);
	}

	/**
	 * 根据条件查询
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑ID
	 * @param offset
	 *            当前页数
	 * @param limit
	 *            分页长度
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 返回Map
	 */
	@Override
	public IPage<FileDownObj> search(final String organCode, final long organLogicId, final int offset, final int limit,
			Map<String, Object> property) {
		if (StringUtils.isEmpty(organCode)) {
			return null;
		}
		if (property == null) {
			property = new HashMap<String, Object>(1);
			property.put("organLogicId", organLogicId);
		}
		final IPage<FileDownObj> page = new Page<FileDownObj>(offset, limit);
		final QueryWrapper<FileDownObj> queryWrapper = new QueryWrapper<FileDownObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "DOWNLOAD_TIME" });
		return fileDownDao.selectPage(page, queryWrapper);
	}

	/**
	 * 复制信息
	 *
	 * @param fromObj
	 *            原信息
	 * @param toObj
	 *            新信息
	 */
	private void setForm(final FileDownObj fromObj, final FileDownObj toObj) {
		toObj.setOrganLogicId(fromObj.getOrganLogicId());
		toObj.setFileLogicId(fromObj.getFileLogicId());
		toObj.setObjLogicId(fromObj.getObjLogicId());
		toObj.setDownloadTime(fromObj.getDownloadTime());
		toObj.setMac(StringUtils.trimToEmpty(fromObj.getMac()));
		toObj.setIp(StringUtils.trimToEmpty(fromObj.getIp()));
		toObj.setExt1(StringUtils.trimToEmpty(fromObj.getExt1()));
		toObj.setExt2(StringUtils.trimToEmpty(fromObj.getExt2()));
		toObj.setExt3(StringUtils.trimToEmpty(fromObj.getExt3()));
		toObj.setExt4(StringUtils.trimToEmpty(fromObj.getExt4()));
		toObj.setExt5(StringUtils.trimToEmpty(fromObj.getExt5()));

	}

	/**
	 * 将对象属性替换成数据库列
	 *
	 * @param property
	 *            参数
	 */
	private void replaceProperty(final Map<String, Object> property) {
		if (property != null) {
			if (property.containsKey("organLogicId")) {
				property.put("ORGAN_LOGIC_ID", property.get("organLogicId"));
				property.remove("organLogicId");
			}
			if (property.containsKey("fileLogicId")) {
				property.put("FILE_LOGIC_ID", property.get("fileLogicId"));
				property.remove("fileLogicId");
			}
			if (property.containsKey("objLogicId")) {
				property.put("OBJ_LOGIC_ID", property.get("objLogicId"));
				property.remove("objLogicId");
			}
			if (property.containsKey("downloadTime")) {
				property.put("DOWNLOAD_TIME", property.get("downloadTime"));
				property.remove("downloadTime");
			}
			if (property.containsKey("mac")) {
				property.put("MAC", property.get("mac"));
				property.remove("mac");
			}
			if (property.containsKey("ip")) {
				property.put("IP", property.get("ip"));
				property.remove("ip");
			}
			if (property.containsKey("ext1")) {
				property.put("EXT1", property.get("ext1"));
				property.remove("ext1");
			}
			if (property.containsKey("ext2")) {
				property.put("EXT2", property.get("ext2"));
				property.remove("ext2");
			}
			if (property.containsKey("ext3")) {
				property.put("EXT3", property.get("ext3"));
				property.remove("ext3");
			}
			if (property.containsKey("ext4")) {
				property.put("EXT4", property.get("ext4"));
				property.remove("ext4");
			}
			if (property.containsKey("ext5")) {
				property.put("EXT5", property.get("ext5"));
				property.remove("ext5");
			}

		}
	}
}